package com.atguigu.gmall.seckill.listener;

import com.atguigu.gmall.seckill.service.SeckillGoodsService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/18 19:12 星期二
 * description: 监听商品活动结束后数据同步到数据库的消息消费者
 */
@Component
@Log4j2
public class SeckillGoodsStockFromRedisToDbListener {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    /**
     * 将Redis中的商品库存同步至数据库
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "seckill_goods_delay_normal_queue")
    public void seckillGoodsStockFromRedisToDb(Channel channel, Message message){
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取需要同步的时间段
        String time = new String(message.getBody());
        try {
            //同步商品的库存数据到数据库中去
            seckillGoodsService.updateSeckillGoodsStock(time);
            //确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                //拒绝过保存到日志,消息拒绝消费并丢弃
                log.error("商品活动结束同步库存失败,原因为:" + e.getMessage());
                log.error("商品活动结束同步库存失败,失败的时间段为:" + time);
                channel.basicReject(deliveryTag,false);
            }catch (Exception e1){
                log.error("商品活动结束同步库存失败拒绝消息失败,原因为:" + e.getMessage());
                log.error("商品活动结束同步库存失败拒绝消息失败,失败的时间段为:" + time);
            }
        }
    }
}
